package website.haicheng.server.util;

import cn.hutool.json.JSONUtil;
import website.haicheng.server.model.vo.Resp;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author: 582895699@qq.com
 * @Desctription: 编码
 * @Date: Created in 2021/12/1 15:39
 */
@Slf4j
@ChannelHandler.Sharable
public class MessageEncode extends MessageToByteEncoder<Resp> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Resp resp, ByteBuf byteBuf) throws Exception {
        Channel channel = channelHandlerContext.channel();
        String jsonStr = JSONUtil.toJsonStr(resp);
        byte[] bytes = jsonStr.getBytes();
        byteBuf.writeInt(bytes.length);
        byteBuf.writeBytes(bytes);
        channel.flush();
    }
}
